import React, { useRef, useState } from 'react';

const CameraCapture: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [sending, setSending] = useState<boolean>(false);

  const captureImage = async () => {
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');

      if (context) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);

        const imageData = canvas.toDataURL('image/jpeg'); // 可以使用 'image/png'

        // 发送图像数据到后端
        setSending(true);
        try {
          // const response = await fetch('/uploadImage', {
          //   method: 'POST',
          //   headers: {
          //     'Content-Type': 'application/json',
          //   },
          //   body: JSON.stringify({ image: imageData }),
          // });
          // 处理后端响应
        } catch (error) {
          // 处理错误
        } finally {
          setSending(false);
        }
      }
    }
  };

  return (
    <div>
      <video ref={videoRef} width="640" height="480" autoPlay />
      <canvas ref={canvasRef} style={{ display: 'none' }} />
      <button onClick={captureImage} disabled={sending}>
        拍摄并发送
      </button>
    </div>
  );
};

export default CameraCapture;
